package controller

import (
	"fmt"
	"github.com/wycto/weigo"
	"github.com/wycto/weigo/datatype"
	"io/ioutil"
	"net/url"
	"os"
	"runtime"
	"strings"
)

type IndexController struct {
	weigo.Controller
}

func (c *IndexController) Index() {
	c.ShowHtml("")
}

func (c *IndexController) List() {
	sysType := runtime.GOOS

	path := c.Context.Post.GetString("path")
	prePath := c.Context.Post.GetString("path")
	name := c.Context.Post.GetString("name")

	path = strings.Replace(path, "\\", weigo.DS, -1)

	if name != "" {
		path = path + name + weigo.DS
	}

	data := datatype.Row{}
	list := datatype.Rows{}

	if sysType == "windows" && path == "" {
		drives := GetLogicalDrives()
		for _, name = range drives {
			row := datatype.Row{}
			row.Set("name", name)
			row.Set("size", 0)
			row.Set("mode", "")
			row.Set("mod_time", "")
			row.Set("is_dir", true)
			list = append(list, &row)
		}

	} else {
		if path == "" {
			path = weigo.DS
		}

		files, _ := ioutil.ReadDir(path)
		for _, file := range files {
			row := datatype.Row{}
			row.Set("name", file.Name())
			row.Set("size", file.Size())
			row.Set("mode", file.Mode())
			row.Set("mod_time", file.ModTime().Format("2006-01-02 15:04:05"))

			if sysType == "windows" {
				row.Set("is_dir", file.IsDir())
			} else {
				row.Set("is_dir", c.isDir(path+weigo.DS+file.Name()))
			}

			list = append(list, &row)
		}

	}

	path = strings.Replace(path, "\\", "/", -1)

	if path == "/" {
		prePath = "/"
	}

	if name == "" && path != "/" {
		prePathArr := strings.FieldsFunc(path, func(r rune) bool {
			return r == '/'
		})

		length := len(prePathArr)
		if length > 0 {
			prePath = "/"
			for i := 0; i < len(prePathArr)-1; i++ {
				prePath += prePathArr[i] + "/"
			}
		}
	}

	if sysType == "windows" {
		path = strings.TrimLeft(path, "/")
		prePath = strings.TrimLeft(prePath, "/")
	}

	data.Set("prePath", prePath)
	data.Set("path", path)
	data.Set("list", list)
	c.ResponseSuccess("OK", data)
}

func (c IndexController) Download() {
	path := c.Context.Get.GetString("path")
	name := c.Context.Get.GetString("name")

	file, err := os.Open(path + name)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()
	content, err := ioutil.ReadAll(file)
	fileNames := url.QueryEscape(name) // 防止中文乱码

	c.Context.ResponseWriter.Header().Add("Content-Type", "application/octet-stream")
	c.Context.ResponseWriter.Header().Add("Content-Disposition", "attachment; filename=\""+fileNames+"\"")

	if err != nil {
		fmt.Println("Read File Err:", err.Error())
	} else {
		c.Context.ResponseWriter.Write(content)
	}
}

func (c *IndexController) isDir(path string) bool {
	s, err := os.Stat(path)

	if err != nil {
		return false

	}
	return s.IsDir()
}

func GetLogicalDrives() []string {

	var drivesAll = []string{"A:", "B:", "C:", "D:", "E:", "F:", "G:", "H:", "I:", "J:", "K:", "L:", "M:", "N:", "O:", "P:", "Q:", "R:", "S:", "T:", "U:", "V:", "W:", "X:", "Y:", "Z:"}
	var drives []string

	for _, drive := range drivesAll {
		files, _ := ioutil.ReadDir(drive)
		has := false
		for _, _ = range files {
			has = true
		}

		if has == true {
			drives = append(drives, drive)
		}
	}
	return drives
}
